package com.dao;

import com.bean.Comment;
import com.utils.DBHelper;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.math.BigDecimal;
import java.sql.Connection;
import java.util.List;

public class CommentDao {
    /**
     * 获取所有评论方法
     * @param id
     * @return
     * @throws Exception
     */
    public List<Comment> getComByPostId(int id) throws Exception {
        Connection conn = DBHelper.getConnection();
        String sql = "select id, content, author, created from comment where postid = ? order by created desc";
        System.out.println("要执行的语句是：" + sql);

        try {
            return new QueryRunner().query(
                    conn, sql, new BeanListHandler<>(Comment.class), id
            );
        } finally {
            DbUtils.closeQuietly(conn);
        }
    }

    /**
     * 添加评论的方法
     * @param comment 要插入的对象
     * @return 返回一个带主键的 Comment 对象
     * @throws Exception
     */
    public Comment addComment(Comment comment) throws Exception {
        Connection conn = DBHelper.getConnection();
        String sql = "insert into comment (postid, author, content) values (?, ?, ?)";
        Object[] params = {
                comment.getPost().getId(), comment.getAuthor(), comment.getContent()
        };
        try {
            // 添加第三个参数，表明需要返回一个 Long 类型的主键
            // 所以，它返回的就是主键
            BigDecimal bigDecimal = new QueryRunner().insert(conn, sql, new ScalarHandler<>(), params);
            comment.setId(bigDecimal.longValue());
            return comment;
        } finally {
            DbUtils.closeQuietly(conn);
        }
    }
}
